//package com.yunxin.admin.system.api.core.user;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.collection.ListUtil;
//import cn.hutool.core.date.DateField;
//import cn.hutool.core.date.DateTime;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.exceptions.ExceptionUtil;
//import cn.hutool.core.util.ObjectUtil;
//import cn.hutool.crypto.SecureUtil;
//import cn.hutool.http.HttpRequest;
//import cn.hutool.http.HttpResponse;
//import cn.hutool.http.Method;
//import cn.hutool.json.JSONObject;
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.yunxin.common.result.PageResult;
//import com.yunxin.common.utils.JacksonUtils;
//import com.yunxin.core.application.admin.team.DistributeDo;
//import com.yunxin.core.application.admin.team.Team;
//import com.yunxin.core.application.admin.team.TeamTaskDistribute;
//import com.yunxin.core.application.assembler.UserInfoAssembler;
//import com.yunxin.core.application.command.user.UserInfoPageCommand;
//import com.yunxin.core.application.dto.user.UserInfoPageDTO;
//import com.yunxin.core.application.service.UserQueryAdminService;
//import com.yunxin.core.domain.model.contact.ContactMessageSendTaskDetail;
//import com.yunxin.core.domain.model.contact.ContactMessageSendTaskDetailRepository;
//import com.yunxin.core.infra.common.contact.enums.PassiveTriggerEnum;
//import com.yunxin.core.infra.persistence.entity.user.UserInfoDO;
//import com.yunxin.core.infra.persistence.entity.user.query.condition.UserPageCondition;
//import com.yunxin.core.infra.persistence.mapper.user.UserInfoExtendMapper;
//import com.yunxin.core.utils.infra.support.lock.DistributedLock;
//import com.yunxin.core.utils.infra.support.lock.DistributedLockFactory;
//import com.yunxin.core.utils.infra.support.lock.TaskLockKey;
//import com.yunxin.statistics.application.dto.UserAllocationStatisticsListDTO;
//import com.yunxin.statistics.application.service.StatisticsQueryAdminService;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import java.net.InetAddress;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.*;
//import java.util.function.Function;
//import java.util.stream.Collectors;
//
//import com.yunxin.core.domain.model.contact.ContactMessageTemplateRepository;
//
//@Component
//@RequiredArgsConstructor
//@Slf4j
//public class FqlSendMsgTask {
//    @Autowired
//    private ContactMessageSendTaskDetailRepository messageSendTaskDetailRepository;
//    @Autowired
//    private UserQueryAdminService userQueryAdminService;
//
//
//    @Value("${sms.gateway.url}")
//    private String url;
//
//    @Value("${sms.gateway.code}")
//    private String code;
//
//    @Value("${sms.gateway.key}")
//    private String key;
//
//    @Value("${sms.gateway.secret}")
//    private String secret;
//
//    @Autowired
//    private ContactMessageTemplateRepository messageTemplateRepository;
//
//    @Autowired
//    private StatisticsQueryAdminService statisticsQueryAdminService;
//
//    private final DistributedLockFactory distributedLockFactory;
//
//    //@Scheduled(cron = "0 0/5 * * * ?") // 每五分钟执行一次
//    public void sendMage() {
//        try {
//            TaskLockKey taskLockKey = TaskLockKey.sendMage_LOCK_KEY;
//            DistributedLock lock = distributedLockFactory.provideDistributedLock(taskLockKey.getPrefix());
//            boolean tryLock = lock.tryLock(taskLockKey.getWaitTime(), taskLockKey.getReleaseTime(), taskLockKey.getTimeUnit());
//            String hostAddress = InetAddress.getLocalHost().getHostAddress();
//            if (tryLock){
//                try {
//                    log.info("发短信任务开始，{}", DateUtil.date());
//                    LocalDateTime now = LocalDateTime.now();
//                    // 五分钟之前的时间
//                    LocalDateTime fiveMinutesBefore = now.minusMinutes(5);
//
//                    // 格式化时间
//                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                    String endTime = now.format(formatter);
//                    String startTime = fiveMinutesBefore.format(formatter);
//
//                    List<ContactMessageSendTaskDetail> listTask = messageSendTaskDetailRepository.listMessageSendTaskDetailByTaskCode(PassiveTriggerEnum.FQL_NOTIFY.getTaskCode());
//                    if (CollUtil.isNotEmpty(listTask)) {
//                        ContactMessageSendTaskDetail detail = listTask.get(0);
//                        UserInfoPageCommand command = new UserInfoPageCommand();
//                        command.setStartRegisterTime(startTime);
//                        command.setEndRegisterTime(endTime);
//                        command.setPageNum(1);
//                        command.setPageSize(1000);
//                        command.setChannelId(28L);
//
//                        PageResult<UserInfoPageDTO> result = userQueryAdminService.userPageQuery(command);
//                        List<UserInfoPageDTO> list = result.getData().getList();
//
//                        if (CollUtil.isNotEmpty(list)) {
//                            Set<String> userCodes = list.stream().map(UserInfoPageDTO::getUserCode).collect(Collectors.toSet());
//                            //查询分配次数
//                            List<UserAllocationStatisticsListDTO> userAllocationStatisticsList = statisticsQueryAdminService.listUserAllocationStatistics(userCodes);
//                            Map<String, UserAllocationStatisticsListDTO> userAllocationStatisticsMap = userAllocationStatisticsList.stream().collect(Collectors.toMap(UserAllocationStatisticsListDTO::getUserCode, Function.identity()));
//                            list.forEach(x -> {
//                                UserAllocationStatisticsListDTO userAllocationStatisticsListDTO = userAllocationStatisticsMap.get(x.getUserCode());
//                                if (Objects.nonNull(userAllocationStatisticsListDTO)) {
//                                    x.setAllocationCount(userAllocationStatisticsListDTO.getAllocationCount());
//                                    x.setAllocationTime(userAllocationStatisticsListDTO.getAllocationLatestTime());
//                                    x.setTwoUV(userAllocationStatisticsListDTO.getTwoUV());
//                                }
//                            });
//                            List<String> phones = list.stream().filter(x -> x.getAllocationTime() == null).map(UserInfoPageDTO::getUserPhone).toList();
//
//                            String phone = String.join(",", phones);
//                            // 获取时间戳
//                            long timestamp = System.currentTimeMillis();
//                            // 生成签名
//                            String sign = key + secret + timestamp;
//                            // md5加密
//                            String md5Sign = SecureUtil.md5(sign).toLowerCase();
//
//                            // 短信内容
//                            var templateContent = messageTemplateRepository.getTemplateContentById(detail.getMessageTemplateId());
//                            HttpRequest request = HttpRequest.post(url + "/sms/batch/v1");
//
//                            // 添加参数
//                            JSONObject requestParam = new JSONObject();
//                            requestParam.put("appkey", key);
//                            requestParam.put("appcode", code);
//                            requestParam.put("sign", md5Sign);
//                            requestParam.put("phone", phone);
//                            requestParam.put("msg", templateContent);
//                            requestParam.put("timestamp", timestamp);
//
//                            // 设置请求方式
//                            request.method(Method.POST);
//                            // 传参方式
//                            request.contentType("application/json;charset=utf-8");
//                            // 添加参数
//                            request.body(requestParam.toString());
//                            // 发送请求
//                            HttpResponse response = null;
//                            try {
//                                response = request.execute();
//                            } catch (Exception e) {
//                                log.error("分期乐短信发送请求异常：", ExceptionUtil.stacktraceToString(e));
//                            }
//                            // 获取返回值
//                            String body = response.body();
//                            // 转json
//                            JSONObject jsonObject = new JSONObject(body);
//                            if (!Objects.equals(jsonObject.getStr("code"), "00000")) {
//                                log.error("分期乐提示短信发送异常,异常信息{}", jsonObject.getStr("desc"));
//                            }
//                            log.info("分期乐短信通知成功,客户电话：{}",phone);
//                        }
//
//                    }
//                }finally {
//                    if (lock.isHeldByCurrentThread()) {
//                        lock.unlock();
//                    }
//                }
//            }else {
//                log.info("ip:{},执行FqlSendMsgTask任务失败,获取锁失败......", hostAddress);
//            }
//        }catch (Exception e) {
//            log.error("执行FqlSendMsgTask任务异常", e);
//        }
//    }
//}
